/**
 * 下载附件
 * @param {*} res 响应头请求数据
 * res.data为文件流
 * decodeURIComponent  处理中文解码问题
*/
function downloadFilesFn(res, name) {
  let fileName = "";
  if(res.headers['content-disposition']) {
    let arr = res.headers['content-disposition'].split('filename=');
    fileName = decodeURIComponent(arr[arr.length-1]);
  } else {
    fileName = name;
  }
  const blob = new Blob([res.data])
  if ('download' in document.createElement('a')) {
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
  } else { 
    navigator.msSaveBlob(blob, fileName);
  }
}

/**
 * 附件上传
 * @param {*} file 本地上传文件流 File
 * @param {*} uploadObj 上传附件配置项
 * @param {*} callback 方法回执
 * @returns 
 */
function beforeUploadFn(file, uploadObj={accept: '', size: 10*1024*1024}, callback) {
  const fileTypeArr = uploadObj.accept.split(",");
  const flag = fileTypeArr.some(item=>file.name.endsWith(item));
  if(!flag) {
    this.$message.warning(`只能上传${uploadObj.accept}文件`);
    return;
  }
  if(file.size > uploadObj.size) {
    this.$message.warning(`单个文件不能超过${uploadObj.size/(1024*1024)}M！`);
    return;
  }
  callback(file);
}

/**
 * 删除附件
 * @param {*} callback 
 */
function deleteFileFn(callback) {
  this.$confirm("确定删除当前附件吗？", "提示").then(()=>{
    callback();
  }).catch(()=>{})
}

/**
 * 自定义附件上传图标显示
 * @param {*} fileName 文件名
 * @returns 
 */
function setFileIcon(fileName) {
  let arr = fileName.split('.');
  let fileType = arr[arr.length-1];
  let icon = 'unkown'
  if (['txt'].includes(fileType)) {
      icon = 'txt';
  } else if(['pdf'].includes(fileType)) {
    icon = 'pdf_1'
  } else if(['doc', 'docx', 'wps', 'odt'].includes(fileType)) {
    icon = 'word'
  } else if(['xls' , 'xlsx' , 'et' , 'csv'].includes(fileType)) {
    icon = 'xlsx'
  } else if(['ppt', 'pptx'].includes(fileType)) {
    icon = 'ppt'
  } else if(['mp3'].includes(fileType)) {
    icon = 'music'
  } else if(['m4a', 'wma'].includes(fileType)) {
    icon = 'video'
  } else if(['jpg', 'jpeg', 'gif', 'png', 'bmp', 'gif'].includes(fileType)) {
    icon = 'png'
  }
  return icon;
}

export default {
  downloadFilesFn,
  beforeUploadFn,
  deleteFileFn,
  setFileIcon
}